﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Utilities;
using JuCheap.Core.IService.AppService;
using System.Security.Claims;
using System.Threading.Tasks;
using static JuCheap.Core.Infrastructure.Utilities.Constants;

namespace JuCheap.Core.IdentityServer
{
    /// <summary>
    /// 自定义验证规则
    /// </summary>
    public class JuCheapResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        /// <summary>
        /// 用户服务
        /// </summary>
        public IUserService _userService;
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="userService"></param>
        public JuCheapResourceOwnerPasswordValidator(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 用户登陆信息验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                //登陆
                var loginInfo = await _userService.LoginAsync(context.UserName, context.Password);
                context.Result = new GrantValidationResult(context.UserName, "custom", GetUserClaims(loginInfo));
            }
            catch(BusinessException bsex)
            {
                //验证失败
                var grantResult = new GrantValidationResult(TokenRequestErrors.InvalidGrant, bsex.Message)
                {
                    IsError = true,
                    Error = bsex.Message
                };
                context.Result = grantResult;
            }
        }

        /// <summary>
        /// 可以根据需要设置相应的Claim
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private Claim[] GetUserClaims(CurrentUserDto user)
        {
            return new Claim[]
            {
                new Claim(ClaimType.CompanyId, user.CompanyId),
                new Claim(ClaimType.CompanyName, user.CompanyName),
                new Claim(ClaimType.UserId, user.UserId),
                new Claim(ClaimType.Name, user.LoginName),
                new Claim(ClaimType.UserName, user.Name),
                new Claim(ClaimType.IsAdmin, user.IsAdmin.ToString()),
                new Claim(ClaimType.IsSystemCompany, user.IsSystemCompany.ToString()),
            };
        }
    }
}
